#!/bin/bash

# 工程实践平台状态检查脚本
# 使用方法: ./scripts/status.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查脚本是否在项目根目录运行
check_project_root() {
    if [[ ! -f "pom.xml" ]] && [[ ! -f "app.jar" ]]; then
        log_error "请在项目根目录运行此脚本"
        exit 1
    fi
}

# 检查主应用状态
check_main_app() {
    log_info "检查主应用状态..."
    
    if [[ -f "app.pid" ]]; then
        local PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            log_success "主应用正在运行，PID: $PID"
            
            # 获取进程信息
            local memory=$(ps -o rss= -p $PID | awk '{print $1/1024 " MB"}')
            local cpu=$(ps -o %cpu= -p $PID)
            local uptime=$(ps -o etime= -p $PID)
            
            echo "   内存使用: $memory"
            echo "   CPU使用: $cpu%"
            echo "   运行时间: $uptime"
            
            # 检查端口监听
            if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
                echo "   端口8080: 正在监听"
            else
                echo "   端口8080: 未监听"
            fi
            
            # 检查健康状态
            if command -v curl &> /dev/null; then
                if curl -s http://localhost:8080/actuator/health &> /dev/null; then
                    echo "   健康状态: 正常"
                else
                    echo "   健康状态: 异常"
                fi
            fi
            
            return 0
        else
            log_warning "主应用进程不存在，清理PID文件"
            rm -f app.pid
            return 1
        fi
    else
        log_warning "主应用未运行"
        return 1
    fi
}

# 检查Docker容器状态
check_docker_containers() {
    log_info "检查Docker容器状态..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装"
        return 1
    fi
    
    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动"
        return 1
    fi
    
    local containers=(
        "practice-platform-mysql"
        "practice-platform-redis"
        "practice-platform-rabbitmq"
        "practice-platform-elasticsearch"
    )
    
    local running=0
    local total=${#containers[@]}
    
    for container in "${containers[@]}"; do
        if docker ps | grep -q "$container"; then
            local status=$(docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep "$container")
            echo "✅ $status"
            ((running++))
        else
            echo "❌ $container: 未运行"
        fi
    done
    
    echo
    echo "容器状态: $running/$total 运行中"
    
    # 显示所有相关容器
    echo
    echo "所有相关容器:"
    docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -E "(practice-platform|mysql|redis|rabbitmq|elasticsearch)" || echo "无相关容器运行"
}

# 检查用户环境
check_user_environments() {
    log_info "检查用户环境..."
    
    if [[ -d "users" ]]; then
        local user_dirs=($(find users -maxdepth 1 -type d -name "user*" 2>/dev/null))
        local total_users=${#user_dirs[@]}
        
        if [[ $total_users -gt 0 ]]; then
            echo "发现 $total_users 个用户环境:"
            
            for user_dir in "${user_dirs[@]}"; do
                local user_id=$(basename "$user_dir")
                local compose_file="$user_dir/docker-compose.yml"
                
                if [[ -f "$compose_file" ]]; then
                    echo "  $user_id: 已配置"
                    
                    # 检查用户容器状态
                    local user_containers=$(docker ps --format "{{.Names}}" | grep "$user_id" || true)
                    if [[ -n "$user_containers" ]]; then
                        echo "    运行中的容器:"
                        echo "$user_containers" | while read container; do
                            echo "      - $container"
                        done
                    else
                        echo "    无运行中的容器"
                    fi
                else
                    echo "  $user_id: 未配置"
                fi
            done
        else
            echo "无用户环境"
        fi
    else
        echo "用户目录不存在"
    fi
}

# 检查系统资源
check_system_resources() {
    log_info "检查系统资源..."
    
    echo "磁盘使用情况:"
    df -h . | head -2
    
    echo
    echo "内存使用情况:"
    free -h | head -2
    
    echo
    echo "CPU使用情况:"
    top -bn1 | grep "Cpu(s)" | awk '{print "CPU使用率: " $2}'
    
    echo
    echo "Docker资源使用:"
    if command -v docker &> /dev/null && docker info &> /dev/null; then
        docker system df --format "table {{.Type}}\t{{.TotalCount}}\t{{.Size}}\t{{.Reclaimable}}"
    else
        echo "Docker不可用"
    fi
}

# 检查网络端口
check_network_ports() {
    log_info "检查网络端口..."
    
    local ports=(8080 3306 6379 15672 9200 9090 3000)
    
    echo "端口检查:"
    for port in "${ports[@]}"; do
        if netstat -tlnp 2>/dev/null | grep -q ":$port "; then
            local process=$(netstat -tlnp 2>/dev/null | grep ":$port " | awk '{print $7}')
            echo "  ✅ 端口 $port: 正在监听 ($process)"
        else
            echo "  ❌ 端口 $port: 未监听"
        fi
    done
}

# 检查日志文件
check_log_files() {
    log_info "检查日志文件..."
    
    if [[ -d "logs" ]]; then
        echo "日志文件:"
        for log_file in logs/*.log; do
            if [[ -f "$log_file" ]]; then
                local size=$(du -h "$log_file" | cut -f1)
                local lines=$(wc -l < "$log_file")
                echo "  $(basename "$log_file"): $size, $lines 行"
            fi
        done
        
        # 显示最近的错误日志
        echo
        echo "最近的错误日志 (最后10行):"
        if [[ -f "logs/app.log" ]]; then
            tail -10 logs/app.log | grep -i "error\|exception\|failed" || echo "  无错误日志"
        fi
    else
        echo "日志目录不存在"
    fi
}

# 显示总体状态
show_overall_status() {
    echo
    echo "=========================================="
    echo "总体状态"
    echo "=========================================="
    
    # 主应用状态
    if check_main_app; then
        echo "✅ 主应用: 运行中"
    else
        echo "❌ 主应用: 未运行"
    fi
    
    # Docker状态
    if docker info &> /dev/null; then
        echo "✅ Docker: 运行中"
    else
        echo "❌ Docker: 未运行"
    fi
    
    # 端口状态
    if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
        echo "✅ 端口8080: 正常"
    else
        echo "❌ 端口8080: 异常"
    fi
    
    echo "=========================================="
}

# 显示管理命令
show_management_commands() {
    echo
    echo "=========================================="
    echo "管理命令"
    echo "=========================================="
    echo "启动平台:   ./scripts/start.sh"
    echo "停止平台:   ./scripts/stop.sh"
    echo "重启平台:   ./scripts/restart.sh"
    echo "查看日志:   tail -f logs/app.log"
    echo "清理日志:   ./scripts/clean-logs.sh"
    echo "=========================================="
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台状态检查"
    echo "=========================================="
    echo
    
    # 检查环境
    check_project_root
    
    # 检查各项状态
    show_overall_status
    check_docker_containers
    check_user_environments
    check_network_ports
    check_system_resources
    check_log_files
    
    # 显示管理命令
    show_management_commands
    
    log_success "状态检查完成！"
}

# 执行主函数
main "$@" 